function EEG = cvc_remove_channels(EEG, chfile, sphereflag)
% CVC_REMOVE_CHANNELS
%
%  Synopsis
%  ========
%
%    EEG = cvc_remove_channels(EEG, chfile)
%    EEG = cvc_remove_channels(EEG, chfile, sphereflag)
%
%  -- Author: Mads Dyrholm --
%     Center for Visual Cognition, University of Copenhagen.
%     2009 - June 2012
%
%  Purpose
%  =======
%
%  Remove bad channels from EEG. The bad channels
%  are given by their labels in a textfile with one
%  channel name per line. The channel labels are case
%  sensitive.
%
%  Inputs
%  ======
%
%  sphereflag - (optional) Set to 1 to interpolate
%  spherically instead of removing the channels.

if nargin<3
  sphereflag = 0;
end

EEG.cvc.chfile=chfile;
nochannel = [];
txt=strtrim(textread(chfile,'%s','delimiter','\n'))
for idx = 1:length(EEG.chanlocs)
  el = EEG.chanlocs(idx);
  I = strmatch(el.labels, txt, 'exact');
  if ~isempty(I),
    nochannel = cat(1,nochannel,idx);
  end
end
if ~isempty(nochannel)
  nochannel
  if sphereflag
      % remove the non-EEG channels to avoid EEGLAB error
      EEGchans = eeg_chantype(EEG,'EEG');
      %EEG2 = pop_select(EEG,'channel',EEGchans);
      % do the interpolation
      EEG = pop_interp(EEG, intersect(nochannel,EEGchans), 'spherical');
      % put the non-EEG back in
      %EEG.data(EEGchans,:,:) = EEG2.data(EEGchans,:,:);
      % non-EEG channels are removed instead of interpolated
      nonEEGnochannel = setdiff(nochannel,EEGchans);
      if ~isempty(nonEEGnochannel)
        EEG = pop_select( EEG, 'nochannel', nonEEGnochannel);
      end
  else
    EEG = pop_select( EEG, 'nochannel', nochannel);
  end
end
